package com.yourname.www.listen;

import com.yourname.www.dao.JdbcHelper;
import com.yourname.www.entity.User;
import com.yourname.www.frame.LoginFrame;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class RegisterButtonActionListener implements ActionListener {
    private JTextField usernameText;
    private JPasswordField passwordText;
    private JPasswordField rePasswordText;
    private JFrame jf;
    public RegisterButtonActionListener(JTextField usernameText, JPasswordField passwordText,JPasswordField rePasswordText, JFrame jf){
        this.usernameText = usernameText;
        this.passwordText = passwordText;
        this.rePasswordText = rePasswordText;
        this.jf = jf;
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        //获取用户名和密码
        String username = usernameText.getText().trim();
        //获取密码
        //String password = passwordText.getText().trim(); 该方法已弃用
        String password = new String(passwordText.getPassword()).trim();
        String rePassword = new String(rePasswordText.getPassword()).trim();
        //如果没有输入用户名，弹出提示
        System.out.println("单机事件");
        if("".equals(username)){
            //弹出提示消息
            JOptionPane.showMessageDialog(jf, "用户名不能为空","系统提醒",JOptionPane.WARNING_MESSAGE);
            return ;
        }else if("".equals(password)){
            JOptionPane.showMessageDialog(jf, "密码不能为空","系统提醒",JOptionPane.WARNING_MESSAGE);
            return ;
        }else if(password.length()<6){
            JOptionPane.showMessageDialog(jf, "密码不能长度不能少于6个字符","系统提醒",JOptionPane.WARNING_MESSAGE);
            return ;
        }else if("".equals(rePassword)){
            JOptionPane.showMessageDialog(jf, "确认密码不能为空","系统提醒",JOptionPane.WARNING_MESSAGE);
            return ;
        }else if(rePassword.length()<6){
            JOptionPane.showMessageDialog(jf, "确认密码不能长度不能少于6个字符","系统提醒",JOptionPane.WARNING_MESSAGE);
            return ;
        }else if(!password.equals(rePassword)){
            JOptionPane.showMessageDialog(jf, "两次输入密码不一致","系统提醒",JOptionPane.WARNING_MESSAGE);
            return ;
        }
        //连接数据库 检查用户名是否存在 检查密码是否正确

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        JdbcHelper jdbcHelper = new JdbcHelper();
        boolean isExists = jdbcHelper.checkUserIsExists(user);
        if(!isExists){
            System.out.println("用户名已被注册");
            JOptionPane.showMessageDialog(jf, "用户名已被注册","系统提醒",JOptionPane.WARNING_MESSAGE);
            return ;
        }else if(jdbcHelper.insertRegisterUser(user)){
            jdbcHelper.insertRegisterUser(user);
            JOptionPane.showMessageDialog(jf, "注册成功","系统提醒",JOptionPane.INFORMATION_MESSAGE);
            jf.dispose();
            new LoginFrame();
        }else{
            JOptionPane.showMessageDialog(jf, "注册失败，请联系管理员","系统提醒",JOptionPane.WARNING_MESSAGE);
        }


    }
}
